package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"net/http"
	"react-blog-server/app/param"
	"react-blog-server/common/response"
)

func NewTableHttp(group *gin.RouterGroup) {
	group.GET("/tables", QueryTables)
	group.GET("/database", QueryDatabase)
	group.GET("/tableInfo", QueryTableInfo)
}

func QueryTableInfo(c *gin.Context) {
	db, err := OpenMysql("")
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}
	defer func() {
		sqlDB, _ := db.DB()
		sqlDB.Close()
	}()

	DataBase := "center"
	Table := "app_menus"

	var res struct {
		FieldInfos []param.FieldInfo `json:"fieldInfos"`
		Idxs       []param.IndexInfo `json:"idxs"`
	}

	if err := db.Raw(fmt.Sprintf("SHOW FULL FIELDS FROM `%s`.`%s`", DataBase, Table)).Scan(&res.FieldInfos).Error; err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}

	if err := db.Raw(fmt.Sprintf("SHOW INDEX FROM `%s`.`%s`", DataBase, Table)).Scan(&res.Idxs).Error; err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}

	response.Success(c, res)
}

func QueryTables(c *gin.Context) {
	db, err := OpenMysql("center")
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}

	defer func() {
		sqlDB, _ := db.DB()
		sqlDB.Close()
	}()

	sql := "SHOW TABLES;"
	rows, err := db.Raw(sql).Rows()
	if err != nil || rows == nil {
		response.Fail(c, http.StatusInternalServerError, "执行失败")
	}

	var Results []string
	for rows.Next() {
		var table string
		_ = rows.Scan(&table)
		fmt.Println(table)
		Results = append(Results, table)
	}
	response.Success(c, Results)
}

func QueryDatabase2(c *gin.Context) {
	db, err := OpenMysql("")
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}

	defer func() {
		sqlDB, _ := db.DB()
		sqlDB.Close()
	}()

	var Results []string
	rows, err := db.Table("information_schema.SCHEMATA").Select("SCHEMA_NAME").Rows()
	for rows.Next() {
		var database string
		rows.Scan(&database)
		Results = append(Results, database)
	}
	response.Success(c, Results)
}

func QueryDatabase(c *gin.Context) {
	db, err := OpenMysql("")
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}

	defer func() {
		sqlDB, _ := db.DB()
		sqlDB.Close()
	}()

	sql := "SHOW DATABASES;"
	rows, err := db.Raw(sql).Rows()
	if err != nil || rows == nil {
		response.Fail(c, http.StatusInternalServerError, "执行失败")
	}

	var Results []string
	for rows.Next() {
		var database string
		_ = rows.Scan(&database)
		Results = append(Results, database)
	}
	response.Success(c, Results)
}

func OpenMysql(database string) (db *gorm.DB, err error) {
	Username := "root"
	ps := "Qq123123"
	IP := "localhost"
	Port := 3306

	dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", Username, ps, IP, Port, database)
	return gorm.Open(mysql.Open(dsn), &gorm.Config{})
}

func ScanDataRows() {

}
